<template>
  <el-card shadow="hover" class="mt-20">
    <el-form
      label-width="100px"
      ref="skuFormRef"
      :model="skuFormData"
      :rules="skuFormDataRules"
    >
      <el-form-item label="SPU名称">{{
        spuSaleAttrListItem.spuName
      }}</el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input placeholder="请输入SKU名称" v-model="skuFormData.skuName" />
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          :min="0"
          controls-position="right"
          class="sku-input-number"
          v-model="skuFormData.price"
        />
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input-number
          :min="0"
          controls-position="right"
          class="sku-input-number"
          v-model="skuFormData.weight"
        />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          placeholder="请输入规格描述"
          type="textarea"
          :rows="3"
          v-model="skuFormData.skuDesc"
        />
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row class="attr-row">
          <el-col
            :xs="24"
            :md="12"
            :lg="8"
            :xl="6"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <div class="attr-wrap">
              <div class="attr-name">{{ attr.attrName }}</div>
              <el-select v-model="skuFormData.skuAttrValueList[index]">
                <el-option
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row class="attr-row">
          <el-col
            :xs="24"
            :md="12"
            :lg="8"
            :xl="6"
            v-for="(saleAttr, index) in spuSaleAttrList"
            :key="saleAttr.id"
          >
            <div class="attr-wrap">
              <div class="attr-name">{{ saleAttr.saleAttrName }}</div>
              <el-select v-model="skuFormData.skuSaleAttrValueList[index]">
                <el-option
                  v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                  :key="saleAttrValue.id"
                  :label="saleAttrValue.saleAttrValueName"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}:`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="skuImageList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="60" align="center" />
          <el-table-column label="图片" align="center">
            <template v-slot="{ row }">
              <el-image :src="row.imgUrl" class="sku-img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName" align="center" />
          <el-table-column label="操作" align="center">
            <template v-slot="{ row, $index }">
              <el-tag type="success" v-if="row.isDefault === '1'">默认</el-tag>
              <el-button
                type="primary"
                size="small"
                v-else
                @click="setDefaultImg(row, $index)"
              >
                设置默认图片
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addSku">保存</el-button>
        <el-button @click="goSpuList">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  name: "AddSku",
  data() {
    return {
      attrList: [],
      spuSaleAttrList: [],
      skuImageList: [],
      skuFormData: {
        skuName: "",
        price: 0,
        weight: 0,
        skuDesc: "",
        skuAttrValueList: [],
        skuSaleAttrValueList: [],
        skuImageList: [],
        skuDefaultImg: "",
      },
      skuFormDataRules: {
        skuName: [
          { required: true, message: "请输入SKU名称", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        weight: [{ required: true, message: "请输入重量", trigger: "blur" }],
        skuDesc: [
          { required: true, message: "请输入SKU描述", trigger: "blur" },
        ],
        skuAttrValueList: [
          { required: true, validator: this.skuAttrValueListValidator },
        ],
        skuSaleAttrValueList: [
          { required: true, validator: this.skuSaleAttrValueListValidator },
        ],
        skuImageList: [
          { required: true, validator: this.skuImageListValidator },
        ],
        skuDefaultImg: "",
      },
    };
  },
  methods: {
    // ...mapActions("spu", ["getSpuImageList"]),
    ...mapMutations("spu", ["RESET_SPUSALEATTRLISTITEM"]),
    // 平台属性检验规则
    skuAttrValueListValidator(rule, value, callback) {
      if (!value.filter(Boolean).length) {
        callback(new Error("请至少选择一个平台属性"));
        return;
      }
      callback();
    },
    // 销售属性检验规则
    skuSaleAttrValueListValidator(rule, value, callback) {
      if (!value.filter(Boolean).length) {
        callback(new Error("请至少选择一个销售属性"));
        return;
      }
      callback();
    },
    // 图片列表检验规则
    skuImageListValidator(rule, value, callback) {
      if (!value.filter(Boolean).length) {
        callback(new Error("请至少选择一张图片"));
        return;
      }
      if (
        !value.some((item) => item.imgUrl === this.skuFormData.skuDefaultImg)
      ) {
        callback(new Error("请从已选中的图片中设置一张默认图片"));
        return;
      }
      callback();
    },
    // 添加SKU
    async addSku() {
      await this.$refs.skuFormRef.validate();
      const params = {
        ...this.skuFormData,
        category3Id: this.category3Id,
        spuId: this.spuSaleAttrListItem.id,
        tmId: this.spuSaleAttrListItem.tmId,
        skuAttrValueList: this.skuFormData.skuAttrValueList
          .filter(Boolean)
          .map((item) => {
            const [attrId, attrName, valueId, valueName] = item.split(":");
            return {
              attrId: +attrId,
              attrName,
              valueId: +valueId,
              valueName,
            };
          }),
        skuSaleAttrValueList: this.skuFormData.skuSaleAttrValueList
          .filter(Boolean)
          .map((item) => {
            const [
              saleAttrId,
              saleAttrName,
              saleAttrValueId,
              saleAttrValueName,
            ] = item.split(":");
            return {
              saleAttrId: +saleAttrId,
              saleAttrName,
              saleAttrValueId: +saleAttrValueId,
              saleAttrValueName,
            };
          }),
      };
      await this.$api.addSku(params);
      this.$message({
        message: "添加SKU成功",
        type: "success",
      });
      this.goSpuList();
    },
    // 设置默认图片
    setDefaultImg(row) {
      this.skuImageList.forEach((item) => {
        item.isDefault = "0";
      });
      row.isDefault = "1";
      this.skuFormData.skuDefaultImg = row.imgUrl;
    },
    // table中的checkBox选中图片
    handleSelectionChange(val) {
      this.skuFormData.skuImageList = val;
    },
    // 返回SPU列表展示页面
    goSpuList() {
      this.$bus.$emit("updateIsShow", "SpuList");
      // 重置Vuex中的form表单数据
      this.RESET_SPUSALEATTRLISTITEM();
    },
    // 获取平台属性列表
    async getAttrList() {
      const res = await this.$api.getAttrList({
        category1Id: this.category1Id,
        category2Id: this.category2Id,
        category3Id: this.category3Id,
      });
      this.attrList = res.data;
    },
    // 获取销售属性列表
    async getSpuSaleAttrList() {
      const { id } = this.spuSaleAttrListItem;
      const res = await this.$api.getSpuSaleAttrList(id);
      this.spuSaleAttrList = res.data;
    },
    // 获取SPU图片列表
    async getSpuImageList() {
      const { id } = this.spuSaleAttrListItem;
      const res = await this.$api.getSpuImageList(id);
      res.data.forEach((item) => {
        item.isDefault = "0";
      });
      this.skuImageList = res.data;
    },
  },
  mounted() {
    this.getSpuImageList();
    this.getSpuSaleAttrList();
    this.getAttrList();
  },
  computed: {
    ...mapState("spu", ["spuSaleAttrListItem"]),
    ...mapState("category", ["category1Id", "category2Id", "category3Id"]),
  },
};
</script>

<style lang="scss" scoped>
.mt-20 {
  margin-top: 20px;
}
.sku-input-number {
  width: 100%;
}

:deep(.el-input__inner) {
  text-align: left;
}

.attr-row {
  width: 100%;
}
.attr-wrap {
  display: flex;
  margin-bottom: 10px;
}
.attr-name {
  text-align: right;
  flex: 1;
  margin-right: 10px;
}

.sku-img {
  width: 100px;
  height: 100px;
}
</style>
